package org.grottarossa.ui.core.base;


import java.util.Hashtable;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.grottarossa.data.QueryFilter;
import org.grottarossa.ui.core.ApplicationSession;
import org.grottarossa.ui.core.components.ITMSControl;
import org.grottarossa.ui.core.controls.deadline.DeadLineData;
import org.grottarossa.ui.core.controls.skiptask.SkipTaskData;

import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;

/***
 * Classe generica dalla quale devono ereditare le factory dei campi delle form
 * @author 
 *
 */
public abstract class BaseFormFieldFactory extends DefaultFieldFactory
{
	/*** Mappa dei campi ***/
	protected Hashtable<String, Field> m_fields = new Hashtable<String, Field>();
	protected ResourceBundle m_localizer;
	protected ApplicationSession m_appSession;

	public BaseFormFieldFactory(ApplicationSession appSession, ResourceBundle localizer)
	{
		m_appSession = appSession;
		m_localizer = localizer;
	}

	public Field createField(Item item, Object propertyId, Component context)
	{
		Field field = null;
		String label = "";

		try
		{
			label = m_localizer.getString("form.fields.captions." + propertyId.toString().toLowerCase());
		}
		catch(MissingResourceException ex)
		{
			label = "";
		}

		try
		{
			if(m_fields.containsKey(propertyId.toString().toLowerCase()))
				field = m_fields.get(propertyId.toString().toLowerCase());
			else
				field = super.createField(item, propertyId, context);

			field.setWidth(100, Sizeable.UNITS_PERCENTAGE);
			field.setCaption(label);
		}
		catch(Exception ex)
		{
			field = null;
		}

		return field;
	}

	/***
	 * Popola un campo dello step
	 * @param field Campo da popolare
	 * @param fieldName Nome del campo
	 * @param filter Filtro da applicare
	 */
	protected void populateField(ITMSControl field, String fieldName, QueryFilter filter)
	{
		try
		{
			field.populate(m_appSession.getDataSourceProvider().getSource(fieldName, filter));
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}
